package com.sample.snl.frontend.SyntaxAnalysis;

import javax.swing.*;
import java.awt.*;

public class DrawTree extends JFrame {
    static int X;
    static int Space = 30;
    static int Width, High;
    static NewPanel Panel;

    public DrawTree() {
        Panel = new NewPanel();
        Panel.setPreferredSize(new Dimension(Width, High));
        JScrollPane pane = new JScrollPane(Panel);
        add(pane);
    }

    public static int getTreeInf(Node root, int Y) {
        int temp, Length, width = 0;
        String str = "";

        if (!root.hasChild() || (root.getChildren().length == 0)) {
            if (!root.hasChild()) str += root.getValue();
            else str += root.getValue();
            Length = str.length() * 8;
            width = Length + Space;
            root.setLength(Length);
            root.setWidth(width);
            root.setX(X);
            root.setY(Y);
            X += width;
        } else {
            str += root.getValue();
            Length = str.length() * 8;
            root.setLength(Length);
            root.setY(Y);
            temp = X;
            for (int i = 0; i < root.getChildren().length; i++) {
                width += getTreeInf(root.getChildren()[i], Y + 150);
            }
            root.setX(temp + width / 2 - Length / 2);
            if (width < Length) {
                width = Length / 2 + width / 2;
                X += Length - width + Space;
            }
            root.setWidth(width);

        }
        return width;
    }

    public static void drawtree(Node root) {
        X = 20;
        High = getTreeInf(root, 20);
        Width = X;
        Panel.Root = root;

        DrawTree frame = new DrawTree();
        frame.setTitle("Parsing Tree");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
}
